package com.laicunba.ext.web.controller.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.laicunba.pojo.vo.FinancingTargetBidVO;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.StringUtil;
import com.laicunba.ext.pojo.Page;
import com.laicunba.ext.service.SlaveFinancingTargetBidService;
import com.laicunba.ext.web.controller.BaseController;

@Controller
@RequestMapping(value = "/webapi/ext")
public class FinancialBuyHistoryAPIController extends BaseController {
	@Autowired
	private SlaveFinancingTargetBidService slaveFinancingTargetBidService;

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/financial_buy_history.htm", method=RequestMethod.GET)
	public String financingTargetFindbyId(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		String callback = request.getParameter("callback");
		String id = request.getParameter("id");
		if(StringUtil.isEmpty(callback) || StringUtil.isEmpty(id)) {
			json.put("code", ResponseCode.PARAM_ERROR);
			json.put("page", null);
			json.put("data", null);
			return callback + "(" + toJsonObject(json) + ")";
		}
		
		String limit = request.getParameter("limit");
		String pageIndex = request.getParameter("pageIndex");
		if (!StringUtil.isNumber(limit)) {
			limit = "10";
		}
		if(!StringUtil.isNumber(pageIndex) || Integer.parseInt(pageIndex) <= 0) {
			pageIndex = "1";
		}
		
		String targetBuyHistoryJson = CacheUtil.getAttribute("sys.buy.history.target-" + id + ".pageIndex-" + pageIndex +".limit-" + limit);
		if(StringUtil.isNotEmpty(targetBuyHistoryJson)){
			return callback + "(" + targetBuyHistoryJson + ")";
		}
		
		Page page = new Page(Integer.parseInt(pageIndex), Integer.parseInt(limit));
		page.setTotalCount(slaveFinancingTargetBidService.countFinancingTargetBidByTargetId(id));
		List<FinancingTargetBidVO> list = slaveFinancingTargetBidService.findFinancingTargetBidByTargetId(id, page);
		if (list == null || list.isEmpty()) {
			json.put("code", ResponseCode.SUCCESS);
			json.put("page", page);
			json.put("data", null);
		} else {
			json.put("code", ResponseCode.SUCCESS);
			json.put("page", page);
			json.put("data", list);
		}
		targetBuyHistoryJson = toJsonObject(json);
		CacheUtil.setAttribute("sys.buy.history.target-" + id + ".pageIndex-" + pageIndex +".limit-" + limit, targetBuyHistoryJson, 5);
		return callback + "(" + targetBuyHistoryJson + ")";
	}
}
